<?php

class Admin_Models_Logic extends Vlib_Models_Table {
    const TABLE_MEMBER = "member";
    const TABLE_PRODUCT = "product";
    const TABLE_NEWS = "news";
    const TABLE_PRODUCT_CATEGORY = "product_category";
    public function __construct($config = array(), $definition = null) {
        parent::__construct($config, $definition);
    }
    
    public function login($arrUserInfo = array()) {
        $this->_logger->debugIn();
        
        if (!$arrUserInfo) {
            $this->_logger->debugOut();
            return false;
        }
        try {
            // get default db adapter
            $dbAdapter = Zend_Db_Table::getDefaultAdapter();

            // init authentication adapter
            $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
            $authAdapter->setTableName($this->__(self::TABLE_MEMBER))
                    ->setIdentityColumn('member_username')
                    ->setCredentialColumn('member_password')
                    ->setCredentialTreatment('SHA1(?)')
                    ->setIdentity($arrUserInfo ['username'])
                    ->setCredential($arrUserInfo ['password']);

            // init authentication instance
            $auth = Zend_Auth::getInstance();

            // execute authentication
            $result = $auth->authenticate($authAdapter);

            // if user is avaible.
            if ($result->isValid()) {
                $userInfo = $authAdapter->getResultRowObject(null, 'password');
                $authStorage = $auth->getStorage();
                $authStorage->write($userInfo);

                $this->_logger->debugOut();
                return true;
            }
        } catch (Exception $e) {
            $this->_logger->error($e->getMessage());
        }
        
        $this->_logger->debugOut();
        return false;
    }
    
    public function getListProduct($aryCondition = array()){
        $this->_logger->debugIn();
        
        try {       
            // crate select statement
            $select = $this->_db->select()
                    ->from($this->__(self::TABLE_PRODUCT_CATEGORY),array('product_category_id','product_category_name'))
                    ->where('product_category_delete_flag = ?', 0)
                    ->joinLeft($this->__(self::TABLE_PRODUCT),"product_category_id = product_cate_id and product_delete_flag = 0" ,array('product_id','product_cate_id','product_name'));
            if(is_array($aryCondition)) {
                foreach($aryCondition as $key=>$val) :
                    $select->where("$key = ?", $val);
                endforeach;
            }
            $select->order('product_category_order');
            $select->order('product_order');
            $this->_logger->sql($select->__toString());
            
            // fetch data
            $arrResult = $this->_db->fetchAll($select);
            $this->_logger->debugOut();

            return $arrResult;
        } catch (Zend_Db_Exception $e) {
            $this->_logger->error($e->getMessage());
        }
        
        $this->_logger->debugOut();
        return array();
    }
    
    public  function insertProduct($aryParams,&$newId) {
        $this->_logger->debugIn();
        $intIsOk = Vlib_Constant::VLIB_ERR_EX_OTHER;
        try{
            // Insert to database
            $intIsOk = $this->_db->insert($this->__(self::TABLE_PRODUCT), $aryParams);
            $newId = $this->_db->lastInsertId();
            $intIsOk =  ($intIsOk) ? Vlib_Constant::VLIB_OK : Vlib_Constant::VLIB_ERR_EX_OTHER;
        }catch(Zend_Db_Exception $e){
            $intIsOk = Vlib_Constant::VLIB_ERR_DB_EXCEPTION;
        }
        $this->_logger->debugOut();
        return $intIsOk;
    }
    
    public  function updateProduct($aryParams,$prdId,$where=null) {
        $this->_logger->debugIn();
        $intIsOk = Vlib_Constant::VLIB_ERR_EX_OTHER;
        $aryBin = array();
        
        try {
            if($where === null)
                $where = ' product_id = '.(int) $prdId;
            
            $result = $this->_db->update($this->__(self::TABLE_PRODUCT), $aryParams, $where);
            if($result >= 0)
                $intIsOk = 1;
            // write insert sql log
            //$arrSql = $this->getSql();
            //$this->_logger->sql($arrSql->sql, $this->__(self::TABLE_PRODUCT), $arrSql->aryBind);
        } catch (Zend_Db_Exception $e) {
            //$this->_logger->error($e->getMessage(),VLIB_UPDATE);
            $intIsOk = Vlib_Constant::VLIB_ERR_DB_EXCEPTION;
        }
        $this->_logger->debugOut();
        
        return $intIsOk;
    }
    
    public function getOneProduct($aryFieldSelect,$prdId,&$output){
        $this->_logger->debugIn();
        $intIsOk = Vlib_Constant::VLIB_OK;
        try{
           $sql =  $this->_db->select()
                            ->from($this->__(self::TABLE_PRODUCT), $aryFieldSelect)
                            ->where('product_id = ?', $prdId)
                            ->where('product_delete_flag = ?', 0);
           //$this->_logger->sql($sql->__toString());
           $output = $this->_db->fetchRow($sql); 
           if(!$output) {
               $intIsOk = Vlib_Constant::ERROR_NOT_FOUND;
           }
        }catch(Zend_Db_Exception $e){
            //$this->_logger->error($e->getMessage(),VLIB_SELECT);
            $intIsOk = Vlib_Constant::VLIB_ERR_DB_EXCEPTION;
        }
        $this->_logger->debugOut();
        return $intIsOk;
    }
    
    public function getListNews($aryFieldSelect,$aryCondition,$aryConfig,$order,&$output,$limit=null){
        $this->_logger->debugIn();
        $intIsOk = Vlib_Constant::VLIB_OK;
        try{
           $aryBin = array(); 
           
           $where = ' news_delete_flag = ? ';
           $aryBin[] = 0 ;

           if(isset($aryCondition['news_type']) && $aryCondition['news_type'] != '' ) {
                $where .= " AND news_type = ? ";
                $aryBin[] = $aryCondition['news_type'];
           }
           
           if(isset($aryCondition['news_id_large']) && $aryCondition['news_id_large'] != '' ) {
                $where .= " AND news_id > ? ";
                $aryBin[] = $aryCondition['news_id_large'];
           }
           $sql = $this->_db->select()->from($this->__(self::TABLE_NEWS), $aryFieldSelect)
                                       ->where($where);
                      
           if(is_array($order)) {
                foreach($order as $v) :
                    $sql->order($v);
                endforeach;
           } else {
                $sql->order($order);
           }
                                                   
           if($limit !== null) {
                $sql->limit($limit,0);
           }

           $output = $this->_db->fetchAll($sql, $aryBin);
           if(isset($aryConfig['per_page']) && isset($aryConfig['current_page'])) { //paging
                        
                $output = Zend_Paginator::factory($output); //$selectStatement
                $output->setItemCountPerPage($aryConfig['per_page'])
                       ->setCurrentPageNumber($aryConfig['current_page']);
            }
        }catch(Zend_Db_Exception $e){
            //$this->_logger->error($e->getMessage(),VLIB_SELECT);
            $intIsOk = Vlib_Constant::VLIB_ERR_DB_EXCEPTION;
        }
        $this->_logger->debugOut();
        return $intIsOk;
    }
    
     public  function insertNews($aryParams,&$newId) {
        $this->_logger->debugIn();
        $intIsOk = Vlib_Constant::VLIB_ERR_EX_OTHER;
        try{
            // Insert to database
            $intIsOk = $this->_db->insert($this->__(self::TABLE_NEWS), $aryParams);
            $newId = $this->_db->lastInsertId();
            $intIsOk =  ($intIsOk) ? Vlib_Constant::VLIB_OK : Vlib_Constant::VLIB_ERR_EX_OTHER;
        }catch(Zend_Db_Exception $e){
            $intIsOk = Vlib_Constant::VLIB_ERR_DB_EXCEPTION;
        }
        $this->_logger->debugOut();
        return $intIsOk;
    }
    
    public  function updateNews($aryParams,$id,$where=null) {
        $this->_logger->debugIn();
        $intIsOk = Vlib_Constant::VLIB_ERR_EX_OTHER;
        $aryBin = array();
        
        try {
            if($where === null)
                $where = ' news_id = '.(int) $id;
            
            $result = $this->_db->update($this->__(self::TABLE_NEWS), $aryParams, $where);
            if($result >= 0)
                $intIsOk = 1;
            // write insert sql log
            //$arrSql = $this->getSql();
            //$this->_logger->sql($arrSql->sql, $this->__(self::TABLE_PRODUCT), $arrSql->aryBind);
        } catch (Zend_Db_Exception $e) {
            //$this->_logger->error($e->getMessage(),VLIB_UPDATE);
            $intIsOk = Vlib_Constant::VLIB_ERR_DB_EXCEPTION;
        }
        $this->_logger->debugOut();
        
        return $intIsOk;
    }
    
     public function getOneNews($aryFieldSelect,$id,&$output){
        $this->_logger->debugIn();
        $intIsOk = Vlib_Constant::VLIB_OK;
        try{
           $sql =  $this->_db->select()
                            ->from($this->__(self::TABLE_NEWS), $aryFieldSelect)
                            ->where('news_id = ?', $id)
                            ->where('news_delete_flag = ?', 0);
           //$this->_logger->sql($sql->__toString());
           $output = $this->_db->fetchRow($sql); 
           if(!$output) {
               $intIsOk = Vlib_Constant::ERROR_NOT_FOUND;
           }
        }catch(Zend_Db_Exception $e){
            //$this->_logger->error($e->getMessage(),VLIB_SELECT);
            $intIsOk = Vlib_Constant::VLIB_ERR_DB_EXCEPTION;
        }
        $this->_logger->debugOut();
        return $intIsOk;
    }


}